package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"warehouse-management/models"
)

type WarehouseControllers struct {
	beego.Controller
}

func (c *WarehouseControllers) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	address := c.GetString("address")
	cate := c.GetString("cate")

	if title == "" || address == "" || cate == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "请确保所有参数不为空",
			"data": nil,
		}
		_ = c.ServeJSON()
		return
	}

	warehouse := models.Warehouse{
		Model:   gorm.Model{},
		Title:   title,
		Address: address,
		Cate:    cate,
	}

	err := models.DB.Create(&warehouse).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "添加失败",
			"data": nil,
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": nil,
		}
		_ = c.ServeJSON()
	}
}
